package com.ysd.shiro.controller;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ysd.common.utils.Json;
import com.ysd.shiro.entity.User;
import com.ysd.shiro.service.UserService;
import com.ysd.shiro.util.CacheUser;
import com.ysd.shiro.util.Response;
import com.ysd.shiro.util.ResultMsg;

@Slf4j
@RestController
@RequestMapping("/ysd")
public class LoginController {


    private Response response;

    private UserService userService;

    @Autowired
    public LoginController(Response response, UserService userService) {
        this.response = response;
        this.userService = userService;
    }

    /**
     * @return
     */
    @RequestMapping(value = "/notLogin")
    public Json notLogin() {
        return Json.fail(ResultMsg.LOGIN_NOTLOGIN);
    }
    
    /**
     * 设置无权限跳转
     * @return
     */
    @RequestMapping(value = "/notRole")
    public Json notRole() {
        return Json.fail(ResultMsg.LOGIN_NOTROLE);
    }
    
    /**
     * description: 登录
     * @return 登录结果
     */
    @RequestMapping("/login")
    public Response frontLogin(User user,HttpSession session) {
        String username = user.getName();
        String password = user.getLoginPassword();
        if (StringUtils.isBlank(username)) {
            return response.failure(ResultMsg.USERNAME_NO);
        }

        if (StringUtils.isBlank(password)) {
            return response.failure(ResultMsg.PASSWORD_NO);
        }

        //session.setAttribute("userInfo", user);       
        CacheUser loginUser = userService.login(username, password);
        // 登录成功返回用户信息
        return response.success(ResultMsg.LOGIN_SUCCESS, loginUser);
    }
  
    /**
     * description: 返回用户信息
     * @return 
     */
    @RequestMapping("/findUserId")
    public String findUserId(HttpSession session) {
    	User user = (User)session.getAttribute("userInfo");
    	return user.getUserId()+"";
    }
    
    /**
     * description: 退出登录
     */
    @RequestMapping("/logout")
    public Response logOut() {
        userService.logout();
        return response.success(ResultMsg.LOGIN_OUTLOGIN);
    }

}
